import React from "react";
import RedRain from '../redRain'
import './index.css'

export default class RedMoney extends React.Component {
    state={
        count:15,
        money:0,
        eachRedEnvelopes:[],
		showOne:0,
    };

    offsetY =-40;
    speed =100;

    componentDidMount() {
        this.timer = setInterval(() => {
            this.setState({count: --this.state.count})
        }, 1000)
        this.redRainTimer = setInterval(()=>{
            let x = this.props.documentWidth* Math.random()
            if(x > this.props.documentWidth-60){
                x = this.props.documentWidth-60
            }
            if(x < 60){
                x = 60
            }
            let newKey = new Date().getTime()
            this.state.eachRedEnvelopes.push(
                <RedRain
                    key = {newKey}
                    offsetX ={x}
                    offsetY = {this.offsetY}
                    speed = {this.speed}
                    money = {10+Math.random()*10}
                    distance={10}
                    onClick={this.onClick}
                    index={this.state.eachRedEnvelopes.length}
                    delete={this.delete}
                />
            )
        },500)
    }

    componentWillUnmount() {
        clearInterval(this.timer)
        clearInterval(this.redRainTimer)
        this.setState = (state, callback) => {
            return;
        };
    }

    onClick = (clickMoney)=>{
    	this.setState({
			showOne:1,
		})
        const { money } = this.state;
        let totalMoney = parseFloat(money)+parseFloat(clickMoney)
        this.setState({
            money: totalMoney.toFixed(2)
        })
		setTimeout(()=>{
			this.setState({
				showOne:0
			})
		},500)
    }

    delete = (index)=>{
        const {eachRedEnvelopes} = this.state;
        eachRedEnvelopes[index] =undefined;
        this.setState(
            eachRedEnvelopes
        )
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        // console.log(prevProps, prevState, snapshot)
        if(prevState.count<=0){
            clearInterval(this.timer)
            clearInterval(this.redRainTimer)
        }
    }

    render() {
        const {eachRedEnvelopes} = this.state;
        return (
            <div >
                <div className="wrap">
                    {   this.state.count>0?
                        <div>
                            <div className="calcCount">倒计时{this.state.count}s</div>
                            <div className="totalMoney">金币:{this.state.money}</div>
                            {
                                this.state.showOne?<div className="addOne">+1</div>:null
                            }
                            <div className="win">{eachRedEnvelopes}</div>
                        </div>
                       :<div className="showTotal"><span>{this.state.money}</span></div>
                    }
                </div>
            </div>
        )
    }
}
